<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width,initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta content="telephone=no" name="format-detection">
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        h2{
            text-align: center;
            margin: 15px 0;
        }
        canvas{
            background: #ddd;
        }
        .btn{
            padding: 5px 15px;
            border: #eee 1px solid;
            display: inline-block;
            margin: 0 15px;
        }
    </style>
</head>
<body>
<div id="maindiv">
    <h2>
        请在下方输入您的名字
    </h2>
    <canvas id="canvas" height="150">
    </canvas>
    <div style="text-align: center;">
        <span class="btn save">保存</span>
        <span class="btn clear">清空</span>
        <span class="btn back" onclick="back()">返回</span>
    </div>
    <img src="" alt="" id="img">
</div>
<script>
    function back() {
        window.location.href = 'demo3.html';
    }

    var canvas = document.getElementById('canvas');
    canvas.width = document.documentElement.clientWidth;

    var imgUrl = '';

    var ctx = canvas.getContext("2d");
    var maindiv = document.getElementById("maindiv");
    ctx.lineWidth = 2.0;
    ctx.strokeStyle = "blue";
    draw();
    function draw(){
        canvas.addEventListener('touchstart',function (ev) {
            var ev = ev || event;
            ctx.beginPath();//canvas.offsetLeft-maindiv.offsetLeft 这个距离才是canvas距离左侧的真正距离
            ctx.moveTo(ev.targetTouches[0].clientX - canvas.offsetLeft-maindiv.offsetLeft, ev.targetTouches[0].clientY - canvas.offsetTop);
        })
        canvas.addEventListener('touchmove',function (ev) {
            var ev = ev || event;
            ctx.lineTo(ev.targetTouches[0].clientX - canvas.offsetLeft-maindiv.offsetLeft, ev.targetTouches[0].clientY - canvas.offsetTop);
            ctx.stroke();
        });
        canvas.addEventListener('touchend',function (ev) {
            //document.ontouchmove = document.ontouchend = null;
            ctx.closePath();
        });
    }

    document.querySelector(".clear").onclick = function () {
        ctx.clearRect(0,0,canvas.width,canvas.height);
    }
    document.querySelector(".save").onclick = function () {
        imgUrl = canvas.toDataURL("image/png");
        localStorage.setItem('yf-sign',imgUrl);
        window.location.href = 'demo3.html';
    }

    function stopScrolling(event) {
        event.preventDefault();
    }
    document.addEventListener('touchmove',stopScrolling,false);
</script>
</body>
</html>